#!/usr/bin/bash
# Init script for libvirtd on Slackware
# Written by Matteo Bernardini <ponce@slackbuilds.org>
#
# Note that a dnsmasq daemon is started by libvirtd itself to serve
# its virtual network, and possibly can conflict with a dnsmasq
# already running on the system, see
# http://wiki.libvirt.org/page/Libvirtd_and_dnsmasq
# Note also that the tun, vhost_net and kvm related modules are
# automatically loaded at start and removed at stop: edit the
# script if this behaviour conflicts with anything else running
# on your setup

MODULES="tun vhost_net"
PIDFILE="/var/run/libvirt/libvirtd.pid"
TIMEOUT=${TIMEOUT:-40}
OPTS=${OPTS:-" -v -f /etc/libvirt/libvirtd.conf -p $PIDFILE "}

check_running_machines() {

  count=0

  for machine in $(virsh list --name --state-running | grep -v ^$) ; do
    /usr/sbin/virsh shutdown $machine
  done

  echo -n "Waiting machines"

  while [ $(virsh list --name --state-running | grep -v ^$ | wc -l) -gt "0" ]; do
    if [ "$count" -ge "$TIMEOUT" ];then
      break
    fi
    echo -n "."
    count=$(expr $count + 1)
    sleep 1
  done

  echo ""

  if [ $(virsh list --name --state-running | grep -v ^$ | wc -l) -gt "0" ];then

    echo -n "The following machines are still running, forcing shutdown: "
    for machine in $(virsh list --name --state-running | grep -v ^$) ; do
      /usr/sbin/virsh destroy $machine
      echo -n "$machine "
    done

    echo ""
    sleep 2
  fi

}

check_processor() {

  egrep 'vmx' /proc/cpuinfo > /dev/null

  if [ "$?" -eq "0" ];then
    MODULES="$MODULES kvm_intel kvm"
  fi

  check=$?

  egrep 'svm' /proc/cpuinfo > /dev/null

  if [ "$?" -eq "0" ];then
    MODULES="$MODULES kvm_amd kvm"
  fi

  check=$(expr $check + $?)

  if [ $check -eq "2" ];then
    echo "Your system does not support KVM!"
  fi

}

start() {
  if [ -f $PIDFILE ];then
    echo "libvirt is already running..."
    exit 1
  fi
  echo "Starting libvirtd:  /usr/sbin/libvirtd -d "
  mkdir -p $(dirname $PIDFILE)
  check_processor
  /sbin/modprobe -a $MODULES
  /usr/sbin/libvirtd -d -l $OPTS
}

stop() {
  if [ ! -f $PIDFILE ];then
    echo "libvirt is not running..."
    exit 2
  fi
  check_running_machines
  check_processor
  echo "Stopping libvirtd..."
  for network in $(/usr/sbin/virsh net-list | tail -n +3 | awk '{print $1}'); do
    /usr/sbin/virsh net-destroy "$network"
  done
  kill -TERM $(cat $PIDFILE)
  sleep 3
  /sbin/modprobe -ra $MODULES 2>/dev/null
}

case $1 in
start)
  start
  ;;
stop)
  stop
  ;;
restart)
  stop
  sleep 1
  start
  ;;
*)
  echo "Usage: $0 (start|stop|restart)"
  ;;
esac

